package com.ahstu.learning.player;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ahstu.learning.R;
import com.ahstu.learning.SubjectActivity.Subject;
import com.nineoldandroids.view.ViewPropertyAnimator;

import java.io.File;
import java.util.ArrayList;

import bf.cloud.android.playutils.DecodeMode;
import bf.cloud.android.playutils.VodPlayer;

public class VodActivity extends FragmentActivity implements View.OnClickListener, BFMediaPlayerControllerVod.TopMenuBarListener {
    private VodPlayer mVodPlayer = null;
    private BFMediaPlayerControllerVod mMediaController = null;
	private String mUrl = "servicetype=1&uid=44248977&fid=";
//			"servicetype=1&uid=4995606&fid=D754D209A442A6787962AB1552FF9412",
//			"servicetype=1&uid=10279577&fid=7099A94CAA19F4EF2B3760D2395E2CD8"};
	private long mHistory = -1;


	private ArrayList<Fragment> fragments;
	private ViewPager viewPager;
	private TextView tab_game;
	private TextView tab_app;
	private int line_width;
	private View line;
	private String playUrl;
	private ImageView course_backbutton,download_play;
	private TextView course_top_name;
	private DownloadManager downManager;
	private DownLoadCompleteReceiver receiver;
	private String course_name;
    private RelativeLayout top_menubar;
    private BFMediaPlayerControllerVod bf;
    private Subject subject;
    private String course_type; 

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//设置屏幕长亮
		setContentView(R.layout.activity_vod);
		init();
		
		creatframe();
		
	}

	public void creatframe(){
		tab_game = (TextView) findViewById(R.id.tab_game);
		tab_app = (TextView) findViewById(R.id.tab_app);
		line = findViewById(R.id.line);


		// 初始化TextView动画
		ViewPropertyAnimator.animate(tab_app).scaleX(1.2f).setDuration(0);
		ViewPropertyAnimator.animate(tab_app).scaleY(1.2f).setDuration(0);

		fragments = new ArrayList<Fragment>();
		fragments.add(new InfoFragment());
		fragments.add(new CommentFragment());
		line_width = getWindowManager().getDefaultDisplay().getWidth()
				/ fragments.size();
		line.getLayoutParams().width = line_width;
		line.requestLayout();

		viewPager = (ViewPager) findViewById(R.id.viewPager);
		viewPager.setAdapter(new FragmentStatePagerAdapter(
				getSupportFragmentManager()) {

			@Override
			public int getCount() {
				return fragments.size();
			}

			@Override
			public Fragment getItem(int arg0) {
				return fragments.get(arg0);
			}
		});

		viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				changeState(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				float tagerX = arg0 * line_width + arg2 / fragments.size();
				ViewPropertyAnimator.animate(line).translationX(tagerX)
						.setDuration(0);
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		tab_game.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				viewPager.setCurrentItem(1);

			}
		});

		tab_app.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				viewPager.setCurrentItem(0);
			}
		});
	}
	
	private void init() {

        subject = new Subject();

        course_backbutton = (ImageView) findViewById(R.id.course_backbutton);
        download_play= (ImageView) findViewById(R.id.download_play);
		course_top_name= (TextView) findViewById(R.id.course_top_name);
		
        top_menubar = (RelativeLayout) findViewById(R.id.top_menubar);
        bf = (BFMediaPlayerControllerVod) findViewById(R.id.media_controller_vod);
        bf.setTopMenuBarListener(this);
        
		course_backbutton.setOnClickListener(this);
		download_play.setOnClickListener(this);
		
		mMediaController = (BFMediaPlayerControllerVod) findViewById(R.id.media_controller_vod);
		mVodPlayer = (VodPlayer) mMediaController.getPlayer();
		// 预设一个DataSource
		mVodPlayer.setDecodeMode(DecodeMode.HARD);//设置视频解码为硬解
		String palyId=getIntent().getStringExtra("playId");
		mVodPlayer.setDataSource(mUrl+palyId);
//		long value = mVodPlayer.getCurrentPosition();//获取当前播放位置
//		mMediaController.setAutoChangeScreen(true);//自动适配翻转屏幕
		mVodPlayer.start();
		
		playUrl=getIntent().getStringExtra("playUrl");
		course_name=getIntent().getStringExtra("course_name");
        course_top_name.setText(course_name);
		
        // 下载按钮服务
        downManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);// 下载服务
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);// 下载完整的行动
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);// 单击行动的通知
        receiver = new DownLoadCompleteReceiver();
        registerReceiver(receiver, filter);

//		LayoutInflater factorys = LayoutInflater.from(VodActivity.this);
//		final View infofragment = factorys.inflate(R.layout.infofragment, null);
//		TextView course_info = (TextView) infofragment.findViewById(R.id.course_info);
//		course_info.setText(getIntent().getStringExtra("course_info"));
//		Toast.makeText(VodActivity.this,getIntent().getStringExtra("course_info")+"111111",Toast.LENGTH_SHORT).show();

        course_type = subject.getCourse_number();
    }

	@Override
	protected void onPause() {
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//取消屏幕长亮
		mHistory = mVodPlayer.getCurrentPosition();
		new Handler().post(new Runnable() {
			
			@Override
			public void run() {
				mVodPlayer.stop();
			}
		});
		super.onPause();
	}

	@Override
	protected void onStart() {
		//不建议在生命周期直接调用player。建议添加异步调用
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				if (mHistory > 0){
					mVodPlayer.start((int) mHistory);
					mHistory = -1;
				}
			}
		}, 100);
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		mVodPlayer.release();
		mVodPlayer = null;
		try {
			mMediaController.finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
        unregisterReceiver(receiver);
        super.onDestroy();
    }


	/* 根据传入的值来改变状态 */
	private void changeState(int arg0) {
		if (arg0 == 0) {
            tab_app.setTextColor(getResources().getColor(R.color.blue));
            tab_game.setTextColor(getResources().getColor(R.color.color_1e1e1e));
            ViewPropertyAnimator.animate(tab_app).scaleX(1.2f).setDuration(200);
            ViewPropertyAnimator.animate(tab_app).scaleY(1.2f).setDuration(200);
			ViewPropertyAnimator.animate(tab_game).scaleX(1.0f)
					.setDuration(200);
			ViewPropertyAnimator.animate(tab_game).scaleY(1.0f)
					.setDuration(200);

		} else {
            tab_game.setTextColor(getResources().getColor(R.color.blue));
            tab_app.setTextColor(getResources().getColor(R.color.color_1e1e1e));
            ViewPropertyAnimator.animate(tab_app).scaleX(1.0f).setDuration(200);
            ViewPropertyAnimator.animate(tab_app).scaleY(1.0f).setDuration(200);
			ViewPropertyAnimator.animate(tab_game).scaleX(1.2f)
					.setDuration(200);
			ViewPropertyAnimator.animate(tab_game).scaleY(1.2f)
					.setDuration(200);
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()){
			case R.id.course_backbutton:
				finish();
				break;
			case R.id.download_play:
				downPlay();
				break;
			default:break;
		}
	}

	private void downPlay() {
        if (playUrl == null) {
            Toast.makeText(VodActivity.this, "抱歉，视频地址解析错误或暂不支持下载",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (new File("/sdcard/diandixuetang/" + course_type + "/" + course_name + ".mp4").exists()) 
            Toast.makeText(VodActivity.this,course_name + " 视频文件已存在！",
                    Toast.LENGTH_SHORT).show();
        else {
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(playUrl));
            Toast.makeText(VodActivity.this, course_name + " 视频正在下载。。。",
                    Toast.LENGTH_SHORT).show();

            // 设置通知栏标题
            request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);//
            request.setTitle(course_name);
            request.setDescription("正在下载...");
            request.setAllowedOverRoaming(false);// 是否同意漫游状态下 执行操作
            // 设置文件存放目录
            request.setDestinationInExternalPublicDir("diandixuetang/" + course_type, course_name + ".mp4");
            downManager.enqueue(request);
        }
	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            String comment = data.getExtras().getString("comment");
            // Toast.makeText(VodActivity.this,comment,Toast.LENGTH_SHORT).show();


        }


    }

    //隐藏顶部标题栏
    @Override
    public void menubar() {
        top_menubar.setVisibility(View.GONE);
    }

    public void showmenubar() {
        top_menubar.setVisibility(View.VISIBLE);
    }
    
	private class DownLoadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                if (new File("/sdcard/diandixuetang/" + course_type + "/" + course_name + ".mp4").exists()) {
                    Toast.makeText(VodActivity.this, course_name + " 视频已经下载完成！",
                            Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(VodActivity.this, course_name + "任务下载失败",
                            Toast.LENGTH_SHORT).show();
                }


            } else if (intent.getAction().equals(
                    DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
                Toast.makeText(VodActivity.this, "正在下载，不要着急，亲！！！",
                        Toast.LENGTH_SHORT).show();
            }
        }

    }

}
